package org.zjt.thread.interrupt;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.zjt.jsr.aa.Getter;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.concurrent.*;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-05-31 下午2:33
 * @see
 */
@Getter
public class BIOInterruptableOperation implements InterruptableOperation{

    private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();

    private static RequestConfigLoader requestConfigLoader = new RequestConfigLoader();


    private final LocalDateTime start ;

    private final URL url;

    private final HttpRequest httpRequest;

    public BIOInterruptableOperation(LocalDateTime start, URL url, HttpRequest httpRequest) {
        this.start = start;
        this.url = url;
        this.httpRequest = httpRequest;
    }

    public String doCall() throws  IOException {
        CloseableHttpResponse closeableHttpResponse = null;
        try {
            CloseableHttpClient client = HttpClients.custom()
                    .setConnectionManager(poolingHttpClientConnectionManager)
                    .setDefaultRequestConfig(requestConfigLoader.getRequestConfig())
                    .build();
            HttpGet httpGet = new HttpGet(url.toString());
            closeableHttpResponse = client.execute(httpGet);

            return EntityUtils.toString(closeableHttpResponse.getEntity());
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //关闭stream流，但不是关闭链接，链接归还给pool
            EntityUtils.consume(closeableHttpResponse.getEntity());
        }
    }


    @Override
    public String call() throws Exception {
        return doCall();
    }

    @Override
    public LocalDateTime getStart() {
        return start;
    }
}
